package com.oig.sys.msg.im.handler.impl;

import cn.hutool.http.ContentType;
import cn.hutool.http.Header;
import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSON;
import com.google.common.base.Throwables;
import com.oig.common.util.JsonUtil;
import com.oig.sys.msg.constants.MsgEnums;
import com.oig.sys.msg.im.domain.account.EnterpriseWeChatRobotAccount;
import com.oig.sys.msg.im.domain.wechat.robot.EnterpriseWeChatRobotParam;
import com.oig.sys.msg.im.domain.wechat.robot.EnterpriseWeChatRootResult;
import com.oig.sys.msg.im.handler.BaseHandler;
import com.oig.sys.msg.vo.NoticeMsgVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * 企业微信群机器人 消息处理器
 */
@Slf4j
@Component
public class EnterpriseWeChatRobotHandler extends BaseHandler {

    public EnterpriseWeChatRobotHandler() {
        channelCode = MsgEnums.MsgChannel.ENTERPRISE_WE_CHAT_ROBOT.getCode() + MsgEnums.MsgChannel.ENTERPRISE_WE_CHAT_ROBOT.getNoticeTypeCode();
    }

    @Override
    public boolean handler(NoticeMsgVo noticeMsg) {
        try {
            EnterpriseWeChatRobotAccount account = JsonUtil.toObject(noticeMsg.getChannelConfig(), EnterpriseWeChatRobotAccount.class);
            EnterpriseWeChatRobotParam enterpriseWeChatRobotParam = assembleParam(noticeMsg);
            String result = HttpRequest.post(account.getWebhook()).header(Header.CONTENT_TYPE.getValue(), ContentType.JSON.getValue())
                    .body(JSON.toJSONString(enterpriseWeChatRobotParam))
                    .timeout(2000)
                    .execute().body();
            EnterpriseWeChatRootResult weChatRootResult = JSON.parseObject(result, EnterpriseWeChatRootResult.class);
            if (weChatRootResult.getErrcode() == 0) {
                return true;
            }
            log.error("EnterpriseWeChatRobotHandler#handler fail! result:{},params:{}", JSON.toJSONString(weChatRootResult), JSON.toJSONString(noticeMsg));
        } catch (Exception e) {
            log.error("EnterpriseWeChatRobotHandler#handler fail!e:{},params:{}", Throwables.getStackTraceAsString(e), JSON.toJSONString(noticeMsg));
        }
        return false;
    }

    private EnterpriseWeChatRobotParam assembleParam(NoticeMsgVo noticeMsg) {
        EnterpriseWeChatRobotParam param = EnterpriseWeChatRobotParam.builder()
                .msgType("text").build();
        param.setText(EnterpriseWeChatRobotParam.TextDTO.builder().content(noticeMsg.getContent()).build());
        return param;
    }

}

